package com.cqz.action;

import com.cqz.dao.UserInfo;
import com.cqz.services.TagService;
import com.cqz.services.UserService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class TagAction {

    @Autowired
    private UserService userService;
    @Autowired
    private TagService tagService;
    /**
     * 初始化标签和添加更多标签
     */
    private int limit = 15;
    @RequestMapping("tagAction")
    public String execute(HttpServletRequest request, HttpSession httpSession,
                          String tag_register,
                          @RequestParam(value = "page",defaultValue = "0") String page){
        if (tag_register == null)
            tag_register = (String) httpSession.getAttribute("tag_register");
        int uid=(Integer) httpSession.getAttribute("uid");
        UserInfo userInfo=userService.findUser(uid);
        String []tagNames=tagService.getTags();
        int index = Integer.parseInt(page);
        int start = index * limit;
        int end = start + limit - 1;
        String []tagsForShow=subArray(tagNames,start,end);
        httpSession.setAttribute("tags",tagsForShow);
        if(tagsForShow.length > 0) {
            if (index > 0){
                String appendJson = JSONArray.fromObject(tagsForShow).toString();
                request.setAttribute("appendJson",appendJson);
                return "forward:tagAppendAction";
            }
            else {
                request.setAttribute("tag_register",tag_register);
                return "selectTag";
            }
        }
        else
            return "fail";
    }

    /**
     * 以json形式返回新增的标签信息
     * @param appendJson
     * @return
     */
    @RequestMapping(value = "tagAppendAction",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String tagAppendAction(@RequestAttribute("appendJson") String appendJson) {
        return appendJson;
    }

    /**
     * 截断部分标签信息
     * @param array
     * @param start
     * @param end
     * @return
     */
    private String[] subArray(String[] array,int start,int end)
    {
        if (end >= array.length) {
            String [] shit = new String[1];
            shit[0] = "NO_MORE";
            return shit;
        }
        String [] res = new String [end-start+1];
        for (int i = start;i<=end;i++){
            res[i-start] = array[i];
        }
        return res;

    }
}
